package com.project.psc.mg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.psc.dto.SupplierDto;
import com.project.psc.service.IMessageService;
import com.project.psc.vo.MessageVo;
import com.project.util.Verifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.URI;


/**
 * websocket服务类
 */
@ServerEndpoint("/msg/{token}")
@Component
public class MgWebsocket {

   public static IMessageService messageService;

    //客户端和服务器建立连接时触发
    @OnOpen
    public void onOpen(Session s, @PathParam("token") String token) throws Exception {
        if (token != null && token.length() != 0) {
            while (true){
                String json = Verifier.verifierJwt(token);
                SupplierDto loginUser = JSONObject.parseObject(json, SupplierDto.class);

                MessageVo msg1 = messageService.findMsg(loginUser.getId());
                String s1 = JSON.toJSONString(msg1);

                s.getBasicRemote().sendText(s1);
                Thread.sleep(10000);
            }
        }

    }

    //客户端和服务器断开连接时触发
    @OnClose
    public void onClose(Session s) {
        System.err.println("websocket连接关闭");
    }

    //客户端向服务器发送消息时触发
    @OnMessage
    public void onMessage(String msg, Session s) {


    }

    //websocket发生异常时触发
    @OnError
    public void onError(Throwable e) {
    }


}
